package com.ischoolbar.programmer.controller.admin;

import com.github.pagehelper.util.StringUtil;
import com.ischoolbar.programmer.entity.admin.Authority;
import com.ischoolbar.programmer.entity.admin.Menu;
import com.ischoolbar.programmer.entity.admin.Role;
import com.ischoolbar.programmer.entity.admin.User;
import com.ischoolbar.programmer.service.admin.IAuthorityService;
import com.ischoolbar.programmer.service.admin.IMenuService;
import com.ischoolbar.programmer.service.admin.IRoleService;
import com.ischoolbar.programmer.service.admin.IUserService;
import com.ischoolbar.programmer.service.admin.impl.UserServiceImpl;
import com.ischoolbar.programmer.utils.CpachaUtil;
import com.ischoolbar.programmer.utils.MenuUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/system")
public class SystemController {

    @Autowired
    IUserService userService;

    @Autowired
    IAuthorityService authorityService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IMenuService menuService;

    @RequestMapping("/welcome")
    public String welcome() {
        return "system/welcome";
    }

    /*
    * 后台首页
    * */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request) {
        List<Menu> menuList = (List<Menu>)request.getSession().getAttribute("menuList");
        model.addAttribute("topList", MenuUtil.findTopMenuList(menuList));
        model.addAttribute("secondList", MenuUtil.findAllSecondMenu(menuList));


        return "system/index";
    }

    /*
    * 登录页面
    * */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        return "system/login";
    }

    /*
    * 登录提交
    * */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, String> loginSubmit(User user, String cpacha, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<>();
        if (user == null ) {
            ret.put("type", "error");
            ret.put("msg", "请填写用户信息");
            return ret;
        }

        if (StringUtil.isEmpty(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "请填写用户名");
            return ret;
        }

        if (StringUtil.isEmpty(user.getPassword())) {
            ret.put("type", "error");
            ret.put("msg", "请填写密码");
            return ret;
        }

        if (StringUtil.isEmpty(cpacha)) {
            ret.put("type", "error");
            ret.put("msg", "请填写验证码");
            return ret;
        }

        Object loginCpacha = request.getSession().getAttribute("loginCpacha");
        if (loginCpacha == null) {
            ret.put("type", "error");
            ret.put("msg", "会话信息失效, 请刷新页面");
            return ret;
        }

        if (!cpacha.toLowerCase().equals(loginCpacha.toString().toLowerCase())) {
            ret.put("type", "error");
            ret.put("msg", "验证码错误, 请重新填写");
            return ret;
        }

        User findByUsername = userService.findUserByUsername(user.getUsername());
        if(findByUsername == null) {
            ret.put("type", "error");
            ret.put("msg", "用户不存在");
            return ret;
        }

        if(!findByUsername.getUsername().equals(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "验证码不正确");
            return ret;
        }

        if(!findByUsername.getPassword().equals(user.getPassword())) {
            ret.put("type", "error");
            ret.put("msg", "密码不正确");
            return ret;
        }

        // 通过用户查找角色信息
        Role roleByUser = userService.findRoleByUser(findByUsername.getRoleId());
        // 通过角色id查找权限
        List<Authority> authorityList = authorityService.findAuthorityByRoleId(roleByUser.getId());
        // 通过权限列表拼接菜单id
        String menuIds = "";
        for (Authority authority : authorityList) {
            menuIds += authority.getMenuId() + ",";
        }
        if (!StringUtils.isEmpty(menuIds)) {
            menuIds = menuIds.substring(0, menuIds.length()-1);
        }
        // 批量查找菜单列表
        List<Menu> menuList = menuService.findMenuListBymenusId(menuIds);

        request.getSession().setAttribute("admin", findByUsername);
        request.getSession().setAttribute("role", roleByUser);
        request.getSession().setAttribute("menuList", menuList);



        ret.put("type", "success");
        ret.put("msg", "登录成功");

        return ret;
    }


    /*
    * 验证码
    * */
    @RequestMapping(value = "/get_cpacha", method = RequestMethod.GET)
    public void generateCpacha(
            @RequestParam(value = "vc",required=false, defaultValue = "4") Integer vcodelen,
            @RequestParam(value = "width",required=false, defaultValue = "100") Integer width,
            @RequestParam(value = "height",required=false, defaultValue = "30") Integer height,
            @RequestParam(value = "type",required = true, defaultValue = "loginCpacha") String CpachaType,
            HttpServletRequest request,
            HttpServletResponse response) {
        CpachaUtil cpachaUtil = new CpachaUtil(vcodelen, width, height);
        String cpacha = cpachaUtil.generatorVCode();
        request.getSession().setAttribute("loginCpacha", cpacha);
        BufferedImage bufferedImage = cpachaUtil.generatorRotateVCodeImage(cpacha, true);
        try {
            ImageIO.write(bufferedImage, "gif", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 退出功能
    * */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().setAttribute("role", null);
        request.getSession().setAttribute("admin", null);
        request.getSession().setAttribute("menuList", null);
        return "redirect:index";
    }
}
